package cn.echogo.framework.activity;

import android.os.Bundle;
import cn.echogo.framework.app.EGApplication;
import cn.echogo.framework.core.AsyncExecuteCallback;
import cn.echogo.framework.core.AsyncExecutor;
import cn.echogo.framework.core.AsyncExecutorImp;
import cn.echogo.framework.core.HttpInvoker;
import cn.echogo.framework.core.HttpInvokerImp;
import cn.echogo.framework.core.Sp;
import cn.echogo.framework.core.Support;
import cn.echogo.framework.core.ViewHelper;
import cn.echogo.framework.core.ViewHelperImp;

public abstract class EGActivity extends DebugActivity {

	protected EGApplication application;
	protected AsyncExecutor asyncExecutor;
	protected ViewHelper viewHelper;
	protected HttpInvoker httpInvoker;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (EGApplication) getApplication();
		initSupportLib();
	}

	protected void initSupportLib() {
		Support support = getClass().getAnnotation(Support.class);
		Sp[] sps = support.value();
		for (Sp sp : sps) {
			switch (sp) {
			case asyncExecutor:
				if (this instanceof AsyncExecuteCallback) {
					initAsyncExecutor((AsyncExecuteCallback) this);
				} else {
					throw new RuntimeException("没有实现AsyncExecuteCallback接口");
				}
				break;
			case viewHelper:
				initViewHelper();
				break;
			case httpInvoker:
				initHttpInvoker();
				break;
			}
		}
	}

	private void initAsyncExecutor(AsyncExecuteCallback asyncExecuteCallback) {
		synchronized (this) {
			if (asyncExecutor == null) {
				asyncExecutor = new AsyncExecutorImp();
				asyncExecutor.setAsyncExecuteCallback(asyncExecuteCallback);
			}
		}
	}

	private void initViewHelper() {
		synchronized (this) {
			if (viewHelper == null) {
				viewHelper = new ViewHelperImp(this);
			}
		}
	}

	private void initHttpInvoker() {
		synchronized (this) {
			if (httpInvoker == null) {
				httpInvoker = new HttpInvokerImp();
			}
		}
	}

}
